const fsExtra = require('fs-extra');
const path = require('path');
const { DynamicContent, User, friendList } = require('../../../models');
const { BASE_URL } = require('../../../config');

function deleteDynamicImageFile(io, socket, data, callback) {
    User.findOne({ phone: data.phone })
    .then(user => {
        if (user === null) return callback({ error: '没有该用户' });
        if (user.draft === null) return callback({ error: '没有该用户的草稿' });
        
        DynamicContent.findOne({ _id: user.draft })
        .then(doc => {
            // code 为 0 时删除所有图片，否则删除指定索引的图片
            if (!data.code) {    
                let directoryPath = path.join(__dirname, '../', 'public/userFiles/' + doc.phone + '/userDynamic/' + doc._id);
                fsExtra.emptyDir(directoryPath)
                doc.imageUrls = []; 
            } else {
                if (data.index < 0 || data.index >= doc.imageUrls.length) {
                    return callback({ error: '索引越界' });  
                } 
        
                let url = path.join(__dirname, '../', 'public' + doc.imageUrls[data.index]);
                fsExtra.remove(url)    
                doc.imageUrls.splice(data.index, 1);
            }

            doc.save()
            .then(result => callback({ success: true }))
            .catch(err => callback({ error: '删除【动态图片】操作失败', details: err }));
        })
        .catch(err => callback({ error: '删除【动态图片】操作失败', details: err }));
    })
}

function releaseDynamic(io, socket, data, callback) {
    User.findOne({ phone: data.phone })
    .then(user => {
        if (user.draft === null) return callback({ error: '没有该用户的草稿' });

        DynamicContent.findOne({ _id: user.draft })
        .then(doc => {
            doc.text = data.text;
            doc.time = data.time;

            user.DynamicList.push(doc._id);
            user.draft = null;
            
            doc.save()
            .then(result => {
                callback({ success: true });

                friendList.findOne({ phone: user.phone })
                .populate({
                    path: 'friends.friendId', 
                    select: 'socketId'
                })
                .then(res => {
                    res.friends.map(item => item.friendId.socketId)
                    .forEach(socketId => {
                        if (socketId != '') {
                            doc.imageUrls = doc.imageUrls.map(item => BASE_URL + item);
                            socket.to(socketId).emit('new_dynamic_friend', doc);
                        }
                    })
                })
            })
            .catch(err => callback({ error: '发布动态失败', details: err }));

            user.save()
            .then(result => console.log('【用户】动态列表已更新'))
            .catch(err => callback({ error: '更改【用户】动态列表失败', details: err }));
        })
        .catch(err => callback({ error: '更改【动态】内容失败', details: err }));
    })
    .catch(err => callback({ error: '更改【用户】动态列表失败', details: err })); 
}

module.exports = {
    deleteDynamicImageFile,
    releaseDynamic
};
